package com.bawei.lib_base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bawei.lib_base.res.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.text.SimpleDateFormat

open class BaseViewModel : ViewModel(){
    fun <T> httpRetrofit(s : suspend () -> Res<T>,success : (T) -> Unit){
        viewModelScope.launch {
            try {
                val invoke = s.invoke()
                if (invoke.code == 200){
                    success.invoke(invoke.data)
                }else{
                    Log.d("===",invoke.message)
                }
            }catch (e : Exception){
                Log.d("===",e.message.toString())
            }
        }
    }

    fun mapToBody(map : Any) : RequestBody{
        val toJson = Gson().toJson(map)
        return RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),toJson)
    }

    fun getDataTime(time : Long) :String{
        return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
    }

    fun getTime(time: Long) : String{
        return SimpleDateFormat("HH:mm:ss").format(time)
    }

    fun getData(time: Long) : String{
        return SimpleDateFormat("yyyy-MM-dd").format(time)
    }

    fun getMonth(time: Long) : String{
        return SimpleDateFormat("yyyy-MM").format(time)
    }
}